import React, { useEffect } from 'react';
import { Form, Modal, Input, Select, DatePicker, message } from 'antd';
import PropTypes from 'prop-types';
import './index.less';
import { LEVEL_TEXT, VUL_TYPES } from '@util/constants';
import PocUploader from '../poc-upload';
import { addPOC } from '@api/task';
import _ from 'lodash';
import moment from 'moment';
const { TextArea } = Input;
const { Option } = Select;
const prefixCls = 'poc-modal';
const rules = [{ required: true, message: '必填信息' }];
const sTit = str => '\u00A0\u00A0\u00A0' + str;
const items = [
  { label: '漏洞分类', id: 'vul_category', rules },
  { label: '影响组件', id: 'affected', rules },
  {
    label: sTit('默认端口'),
    id: 'default_ports',
    type: TextArea,
    placeholder: '多个端口用","分隔例如80,443'
  },
  {
    label: sTit('影响范围'),
    id: 'affected_version',
    placeholder: '请输入影响范围，并以英文逗号","做分隔',
    type: TextArea
  },
  { label: sTit('漏洞描述'), id: 'description', type: TextArea },
  { label: sTit('漏洞危害'), id: 'harm', type: TextArea },
  { label: sTit('修复建议'), id: 'suggestion', type: TextArea },
  {
    label: sTit('相关链接'),
    id: 'related',
    placeholder: '请输入相关链接，并以英文逗号","做分隔',
    type: TextArea
  },
  { label: 'POC文件', id: 'file', type: PocUploader, rules },
  { label: '披露时间', id: 'lanched', type: DatePicker, rules },
  { label: sTit('CVE ID'), id: 'cve_id' },
  { label: sTit('CNNVD ID'), id: 'cnnvd_id' },
  { label: sTit('CNVD ID'), id: 'cnvd_id' },
  { label: sTit('CWE'), id: 'cwe' },
  { label: sTit('OWASP'), id: 'owasp', placeholder: '请输入OWASP，并以英文逗号","做分隔' },
  { label: sTit('CSVV 3.0'), id: 'cvss_3' }
];
const PocModal = props => {
  const { value = {}, onOk, onCancel, visible, form } = props;
  const { setFieldsValue, validateFields, getFieldDecorator, resetFields } = form;

  useEffect(() => {
    if (!visible) {
      resetFields();
    } else if (value._id) {
      setFieldsValue({
        ...value,
        lanched: moment(value.lanched),
        // eslint-disable-next-line
        default_ports: _.get(value, 'default_ports', []).join(','),
        // eslint-disable-next-line
        affected_version: _.get(value, 'affected_version', []).join(','),
        related: _.get(value, 'related', []).join(','),
        owasp: _.get(value, 'owasp', []).join(','),
        file: { uploadName: value.poc + '.py' }
      });
    }
  }, [visible, value]);

  const handleOk = () => {
    validateFields((err, res) => {
      if (err) {
        return;
      }
      const params = _.omitBy(res, _.isEmpty);
      // 当文件uploadName为真时，说明文件没有重新上传
      if (params.file.uploadName) {
        delete params.file;
      }
      if (value._id) {
        params._id = value._id;
      }
      const body = new FormData();
      Object.keys(params).forEach(key => body.append(key, params[key]));
      addPOC(body)
        .then(onOk)
        .catch(err => {
          message.error(err.message || '操作失败');
        });
    });
  };
  return (
    <div className={prefixCls}>
      <Modal
        maskClosable={false}
        visible={visible}
        onOk={handleOk}
        className={`${prefixCls}-modal`}
        onCancel={onCancel}
        title={`${value.name ? '修改' : '上传'}POC`}
      >
        <Form className={`${prefixCls}-form`} labelCol={{ span: 6 }} wrapperCol={{ span: 17 }}>
          <Form.Item label={'漏洞名称'}>
            {getFieldDecorator('name', {
              rules: [{ required: true, message: '必填信息' }]
            })(<Input placeholder={'格式： 漏洞名称（CVE编号）'} />)}
          </Form.Item>
          <Form.Item label={'漏洞等级'}>
            {getFieldDecorator('level', {
              rules: [{ required: true, message: '必填信息' }]
            })(
              <Select getPopupContainer={triggerNode => triggerNode.parentNode}>
                {Object.keys(LEVEL_TEXT).map(key => (
                  <Option key={key} value={key}>
                    {LEVEL_TEXT[key]}
                  </Option>
                ))}
              </Select>
            )}
          </Form.Item>
          <Form.Item label={'漏洞类型'}>
            {getFieldDecorator('vul_type', {
              rules: [{ required: true, message: '必填信息' }]
            })(
              <Select getPopupContainer={triggerNode => triggerNode.parentNode}>
                {Object.keys(VUL_TYPES).map(key => (
                  <Option key={key} value={key}>
                    {VUL_TYPES[key]}
                  </Option>
                ))}
              </Select>
            )}
          </Form.Item>
          {items.map(item => {
            const Inputer = item.type || Input;
            return (
              <Form.Item key={item.id} label={item.label}>
                {getFieldDecorator(item.id, {
                  rules: item.rules
                })(<Inputer placeholder={item.placeholder} />)}
              </Form.Item>
            );
          })}
        </Form>
      </Modal>
    </div>
  );
};
PocModal.propTypes = {
  value: PropTypes.object,
  visible: PropTypes.bool,
  onOk: PropTypes.func,
  onCancel: PropTypes.func,
  form: PropTypes.object
};
export default Form.create()(PocModal);
